package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseAppV1;
import com.atguigu.gmall.realtime.bean.TrafficPageViewBean;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2022/12/12 08:43
 */
public class Dws_02_DwsTrafficVcChArIsNewPageViewWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_02_DwsTrafficVcChArIsNewPageViewWindow().init(
            4002,
            2,
            "Dws_02_DwsTrafficVcChArIsNewPageViewWindow",
            Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }
    
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {
        // 1. 先把数据封装到 pojo 中
        SingleOutputStreamOperator<TrafficPageViewBean> beanStream = parseToPojo(stream);
        // 2. 开窗聚合
        SingleOutputStreamOperator<TrafficPageViewBean> resultStream = windowAndAgg(beanStream);
        // 3. 写出到 clickhouse 中
//        writeToClickHouse
        // log4j -> log for java -> log four java -> log4j
        // a2b -> a two b -> a to b
        // i18n -> 国际化
        // json4s -> json for scala
        write2ClickHouse(resultStream);
    }
    
    private void write2ClickHouse(SingleOutputStreamOperator<TrafficPageViewBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_traffic_vc_ch_ar_is_new_page_view_window", TrafficPageViewBean.class));
    }
    
    private SingleOutputStreamOperator<TrafficPageViewBean> windowAndAgg(SingleOutputStreamOperator<TrafficPageViewBean> beanStream) {
        // 1. 设置事件时间 2. keyBy 3. 聚合
       return beanStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TrafficPageViewBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
                    .withIdleness(Duration.ofSeconds(30))  // 可以避免数据倾斜导致的水印不更新
            )
            .keyBy(bean -> bean.getVc() + bean.getCh() + bean.getAr() + bean.getIsNew())
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TrafficPageViewBean>() {
                    @Override
                    public TrafficPageViewBean reduce(TrafficPageViewBean bean1,
                                                      TrafficPageViewBean bean2) throws Exception {
                        bean1.setUvCt(bean1.getUvCt() + bean2.getUvCt());
                        bean1.setPvCt(bean1.getPvCt() + bean2.getPvCt());
                        bean1.setSvCt(bean1.getSvCt() + bean2.getSvCt());
                        bean1.setDurSum(bean1.getDurSum() + bean2.getDurSum());
    
                        return bean1;
                    }
                },
                new ProcessWindowFunction<TrafficPageViewBean, TrafficPageViewBean, String, TimeWindow>() {
                    // 窗口触发计算的执行一次
                    @Override
                    public void process(String key,  // key
                                        Context ctx,  // 从里面获取到窗口信息
                                        Iterable<TrafficPageViewBean> elements, // 有且仅有一个值: 前面聚会的最终结果
                                        Collector<TrafficPageViewBean> out) throws Exception {
                        TrafficPageViewBean bean = elements.iterator().next();
                        
                        // 补充窗口信息
                        bean.setStt(AtguiguUtil.toDatTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.toDatTime(ctx.window().getEnd()));
                        
                        // 把 ts 改成: 数据的统计时间
                        bean.setTs(System.currentTimeMillis());
                        out.collect(bean);
    
                    }
                }
            );
        
    }
    
    private SingleOutputStreamOperator<TrafficPageViewBean> parseToPojo(DataStreamSource<String> stream) {
        return stream
            // 分组的目的: 是为了计算 uv
            .keyBy(json -> JSON.parseObject(json).getJSONObject("common").getString("mid"))
            .map(new RichMapFunction<String, TrafficPageViewBean>() {
                
                private ValueState<String> dateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    dateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("dateState", String.class));
                }
                
                @Override
                public TrafficPageViewBean map(String value) throws Exception {
                    
                    JSONObject obj = JSON.parseObject(value);
                    Long ts = obj.getLong("ts");
                    String today = AtguiguUtil.tsToDate(ts);
                    JSONObject common = obj.getJSONObject("common");
                    JSONObject page = obj.getJSONObject("page");
                    String vc = common.getString("vc");
                    String ch = common.getString("ch");
                    String ar = common.getString("ar");
                    String isNew = common.getString("is_new");
                    
                    Long pvCt = 1L;
                    Long durSum = page.getLong("during_time");
                    
                    Long svCt = 0L;
                    // 如果是新会话, 则把 svCt = 1L;
                    if (page.getString("last_page_id") == null) {
                        svCt = 1L;
                    }
                    
                    Long uvCt = 0L;
                    String date = dateState.value();
                    if (!today.equals(date)) {// 证明是这个 mid 的首次, 或者今天的首次
                        uvCt = 1L;
                        // 更新状态
                        dateState.update(today);
                    }
                    
                    return new TrafficPageViewBean(
                        "", "",
                        vc, ch, ar, isNew,
                        uvCt, svCt, pvCt, durSum,
                        ts
                    );
                }
            });
    }
}
/*
页面浏览数 pv
    dwd_traffic_page

独立访客数 uv
    mid_1
    
    dwd_traffic_page
浏览总时长
    dwd_traffic_page
会话数
    dwd_traffic_page
        找到这个会话的第一条记录
        
        last_page_id = null
-------------

页面日志数据                  pv       uv         sum_time       sv
 版本-渠道-地区-访客类别        1        1/0         1000          1/0


放入到一个 pojo 中

开窗聚和

----------------
窗口处理函数:
    简单
        sum  max min
        maxBy minBy
    
    
    复杂
        reduce
            输入和聚和后的类型一致
        
        aggregate
            不一致
        
        process
            最灵活

 */